const API = '/api/books';

const el = (sel) => document.querySelector(sel);
const form = el('#book-form');
const booksContainer = el('#books');
const msg = el('#msg');
const titleInput = el('#title');
const notesInput = el('#notes');
const idInput = el('#book-id');
const submitBtn = el('#submit-btn');
const cancelBtn = el('#cancel-edit');

function showMessage(text, type='info') {
  msg.textContent = text;
  msg.className = type === 'error' ? 'msg error' : 'msg';
  if (!text) msg.className = 'msg';
  setTimeout(() => {
    // 3s 后自动清除（如果没有被覆盖）
    if (msg.textContent === text) msg.textContent = '';
  }, 3000);
}

async function loadBooks() {
  try {
    const res = await fetch(API);
    if (!res.ok) throw new Error('加载失败');
    const books = await res.json();
    renderBooks(books);
  } catch (err) {
    showMessage('无法加载图书：' + err.message, 'error');
  }
}

function renderBooks(books) {
  if (!books || books.length === 0) {
    booksContainer.innerHTML = `<p class="empty">暂无图书，快添加一本吧。</p>`;
    return;
  }
  booksContainer.innerHTML = books.map(bookCard).join('');
  // 给动态按钮绑定事件（事件委托也可）
  document.querySelectorAll('.btn-edit').forEach(btn => btn.addEventListener('click', onEdit));
  document.querySelectorAll('.btn-delete').forEach(btn => btn.addEventListener('click', onDelete));
  document.querySelectorAll('.btn-view').forEach(btn => btn.addEventListener('click', onView));
}

function bookCard(b) {
  const shortNotes = b.notes ? (b.notes.length > 120 ? b.notes.slice(0, 120) + '…' : b.notes) : '<i>（无笔记）</i>';
  return `
  <div class="card book" data-id="${b.id}">
    <div class="book-head">
      <strong class="book-title">${escapeHtml(b.title)}</strong>
      <div class="book-actions">
        <button class="btn btn-view" data-id="${b.id}">查看</button>
        <button class="btn btn-edit" data-id="${b.id}">编辑</button>
        <button class="btn btn-delete" data-id="${b.id}">删除</button>
      </div>
    </div>
    <div class="book-notes">${escapeHtml(shortNotes)}</div>
  </div>`;
}

function escapeHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const title = titleInput.value.trim();
  const notes = notesInput.value.trim();
  if (!title) {
    showMessage('请填写书名', 'error');
    return;
  }
  const id = idInput.value;
  if (id) {
    // 编辑
    await updateBook(Number(id), { title, notes });
  } else {
    await createBook({ title, notes });
  }
  // 刷新并清空表单（create/update 会自行刷新）
  titleInput.value = '';
  notesInput.value = '';
  idInput.value = '';
  submitBtn.textContent = '添加图书';
  cancelBtn.style.display = 'none';
});

cancelBtn.addEventListener('click', () => {
  idInput.value = '';
  titleInput.value = '';
  notesInput.value = '';
  submitBtn.textContent = '添加图书';
  cancelBtn.style.display = 'none';
});

async function createBook(payload) {
  try {
    const res = await fetch(API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    if (!res.ok) {
      const err = await res.json().catch(()=>({error:'请求失败'}));
      throw new Error(err.error || '添加失败');
    }
    showMessage('添加成功');
    await loadBooks();
  } catch (err) {
    showMessage(err.message, 'error');
  }
}

async function updateBook(id, payload) {
  try {
    const res = await fetch(`${API}/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    if (!res.ok) {
      const err = await res.json().catch(()=>({error:'请求失败'}));
      throw new Error(err.error || '更新失败');
    }
    showMessage('更新成功');
    await loadBooks();
  } catch (err) {
    showMessage(err.message, 'error');
  }
}

async function onDelete(e) {
  const id = e.target.dataset.id;
  if (!confirm('确定删除此图书吗？')) return;
  try {
    const res = await fetch(`${API}/${id}`, { method: 'DELETE' });
    if (!res.ok) {
      const err = await res.json().catch(()=>({error:'请求失败'}));
      throw new Error(err.error || '删除失败');
    }
    showMessage('删除成功');
    await loadBooks();
  } catch (err) {
    showMessage(err.message, 'error');
  }
}

async function onEdit(e) {
  const id = e.target.dataset.id;
  try {
    const res = await fetch(`${API}/${id}`);
    if (!res.ok) throw new Error('无法获取条目');
    const book = await res.json();
    idInput.value = book.id;
    titleInput.value = book.title;
    notesInput.value = book.notes || '';
    submitBtn.textContent = '保存修改';
    cancelBtn.style.display = 'inline-block';
    window.scrollTo({ top: 0, behavior: 'smooth' });
  } catch (err) {
    showMessage(err.message, 'error');
  }
}

async function onView(e) {
  const id = e.target.dataset.id;
  try {
    const res = await fetch(`${API}/${id}`);
    if (!res.ok) throw new Error('无法获取条目');
    const book = await res.json();
    alert(`书名：${book.title}\n\n笔记：\n${book.notes || '(无)'}`);
  } catch (err) {
    showMessage(err.message, 'error');
  }
}

// 初始化
loadBooks();